/*
 * BGMatrix.cpp
 *
 *  Created on: 19/04/2010
 *      Author: Nenem
 */

#include "BGMatrix.h"

BGMatrix::BGMatrix(){}

BGMatrix::BGMatrix(int width, int height) {
	this->height = height;
	this->width = width;

	matrix = new Tile[width * height];

}

BGMatrix::~BGMatrix() {
	delete[] matrix;
}

int BGMatrix::get(int i, int j) {
	if(matrix[j*width + i].rigid)
		return 1;
	else
		return 0;
}

EnumTerrainType BGMatrix::getTerrain(int i, int j){
	return matrix[j*width + i].terrainType;
}

void BGMatrix::set(int i, int j , int value, string terrain){
	if(value == 0){
		matrix[j*width + i].rigid = false;
		if(terrain == "grass")
			matrix[j*width + i].terrainType = GRASS;
		if(terrain == "stairs")
			matrix[j*width + i].terrainType = STAIRS;
		if(terrain == "")
			matrix[j*width + i].terrainType = NORMAL;
	}
	else{
		matrix[j*width + i].rigid = true;
		matrix[j*width + i].terrainType = NORMAL;
	}
}

bool BGMatrix::loadMapFile(string arqName) {

	const int MAX = 80;
	char buff[MAX];
	size_t begin, end;
	string path = getPath() + arqName + "\\";

	arqName = arqName + ".xml";

	ifstream fin((arqName).c_str(), ifstream::in);

	if(fin.good()){

		fin.getline(buff,MAX);
		string line(buff);

		begin = line.find("width=\"");

		if(begin != string::npos){
			begin = line.find("\"", begin + 1);
			end = line.find("\"", begin + 1);
			width = atoi(line.substr(begin + 1,end - begin).c_str());
		}
		begin = line.find("height=\"");
		if(begin != string::npos){
			begin = line.find("\"", begin + 1);
			end = line.find("\"", begin + 1);
			height = atoi(line.substr(begin + 1, end - begin).c_str());
		}

		matrix = new Tile[height*width];
	}
	else{
		cout << "Error loading: " + path + arqName;
		return false;
	}

	int i=0, j=0;

	while(fin.good()){
		fin.getline(buff,MAX);
		string line(buff);
		size_t found = line.find("<tile gid=");
		if(found != string::npos){
			found = line.find("<tile gid=\"0\"");
			if(found != string::npos) {
				found = line.find("type=\"");
				if(found != string::npos){
					end = line.find("\"/>", found + 1);
					set(i, j, 0, line.substr(found + 6, end - found - 6));
				}
				else
					set(i, j, 0, "");
			}
			else {
				set(i, j, 1, "");
			}
			i++;
			if(i > width-1){
				i=0;
				j++;
			}
		}
	}

//	for(j=0; j<height;j++){
//		for(i = 0; i < width;i++){
//			cout << get(i,j);
//		}
//		cout << "\n";
//	}
//	print();
	return true;
}

void BGMatrix::print(){
	for(int j=0; j<height;j++){
		for(int i = 0; i < width;i++){
			cout << get(i,j) << "\t";
		}
		cout << "\n";
	}
}
